<!-- 订单列表 -->
<template>
  <div class="orderList sys-content">
    <page-mod>
      <el-card>
        <div class="query-box">
          <el-form :model="query" inline>
            <el-form-item label="订单编号:">
              <el-input v-model="query.orderCode" placeholder="请输入订单编号" clearable/>
            </el-form-item>
            <el-form-item label="订单类型:">
              <el-select v-model="query.orderType" placeholder="请选择" clearable>
                <el-option label="正常订单" :value="0"/>
                <el-option label="加盟订单" :value="1"/>
              </el-select>
            </el-form-item>
            <el-form-item label="订单状态:">
              <el-select v-model="query.orderStatus" placeholder="请选择" clearable>
                <el-option label="待付款" :value="0"/>
                <el-option label="待发货" :value="1"/>
                <el-option label="已发货" :value="2"/>
                <el-option label="已完成" :value="3"/>
                <el-option label="已关闭" :value="4"/>
              </el-select>
            </el-form-item>
            <el-form-item label="订单来源:">
              <el-select v-model="query.sourceType" placeholder="请选择" clearable>
                <el-option label="APP商城" :value="0"/>
                <el-option label="小程序商城" :value="1"/>
                <el-option label="后台" :value="2"/>
              </el-select>
            </el-form-item>
            <el-form-item label="支付方式:">
              <el-select v-model="query.payType" placeholder="请选择" clearable>
                <el-option label="未支付" :value="0"/>
                <el-option label="支付宝" :value="1"/>
                <el-option label="微信" :value="2"/>
              </el-select>
            </el-form-item>
            <el-form-item label="退款状态:">
              <el-select v-model="query.refundStatus" placeholder="请选择" clearable>
                <el-option label="未退款" :value="0"/>
                <el-option label="退款中" :value="1"/>
                <el-option label="已退款" :value="2"/>
              </el-select>
            </el-form-item>
            <el-form-item label="下单时间:">
              <div style="width: 372px;margin-right: 20px;">
                <el-date-picker 
                  v-model="dates" 
                  type="datetimerange" 
                  value-format="YYYY-MM-DD HH:mm:ss"
                  range-separator="至" 
                  start-placeholder="开始日期" 
                  end-placeholder="结束日期" 
                  style="width: 100%;" 
                  @change="dateChange"/>
              </div>
            </el-form-item>
          </el-form>
          <div class="btns">
            <el-button icon="Search" color="#16b777" @click="load(1)">查询</el-button>
            <!-- <el-button icon="Plus" color="#FFB800" @click="addShow = true">新增</el-button> -->
            <el-button icon="Refresh" color="#FF5722" @click="resetSearch">重置</el-button>
          </div>
        </div>
      </el-card>
    </page-mod>
    <page-mod title="订单数据" icon="PriceTag" :showBtn="false" :padBottom="false">
      <el-card v-loading="loading" element-loading-text="拼命加载中" >
        <el-table :data="dataList" max-height="493" row-key="id" border>
          <el-table-column label="序号" type="index" align="center" width="60"></el-table-column>
          <el-table-column label="订单编号" prop="orderCode" align="center" width="190"></el-table-column>
          <el-table-column label="物流单号" prop="orderCode" header-align="center" width="220">
            <template #default="{row}">
              <div v-for="item in getDelivery(row.deliveryMap)" :key="item.code">
                <el-button type="primary" link @click="doViewLogisticsLog(item.code)">{{item.name + ':' + item.code}}</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="收货人名称" prop="receiveName" align="center"></el-table-column>
          <el-table-column label="收货人电话" prop="receivePhone" align="center" width="120"></el-table-column>
          <el-table-column label="支付金额（元）" prop="payAmount" align="center"></el-table-column>
          <el-table-column label="下单时间" prop="createdTime" align="center" width="170">
            <template #default="{row}">
              <span>{{ $date(row.createdTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单状态" prop="orderStatus" align="center" width="120">
            <template #default="{row}">
              <el-tag v-if="row.orderStatus === 0" type="info">待付款</el-tag>
              <el-tag v-if="row.orderStatus === 1" type="warning">待发货</el-tag>
              <el-tag v-if="row.orderStatus === 2">已发货</el-tag>
              <el-tag v-if="row.orderStatus === 3" type="success">已完成</el-tag>
              <el-tag v-if="row.orderStatus === 4" type="danger">已关闭</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="支付方式" prop="payType" align="center" width="120">
            <template #default="{row}">
              <el-tag v-if="row.payType === 0" type="info">无支付</el-tag>
              <el-tag v-if="row.payType === 1" type="success">支付宝</el-tag>
              <el-tag v-if="row.payType === 2" type="danger">微信</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="付款状态" prop="payStatus" align="center" width="120">
            <template #default="{row}">
              <el-tag :type="row.payStatus ? 'success' : 'danger'">{{ row.payStatus ? '已付款' : '未付款' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="订单来源" prop="sourceType" align="center" width="120">
            <template #default="{row}">
              <el-tag v-if="row.sourceType === 0" type="info">APP</el-tag>
              <el-tag v-if="row.sourceType === 1" type="success">小程序</el-tag>
              <el-tag v-if="row.sourceType === 2" type="danger">后台</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180">
            <template #default="{row}">
              <el-button type="primary" icon="View" link @click="toViewOrder(row.orderId)">查看</el-button>
              <el-divider v-if="row.orderStatus === 1" direction="vertical" />
              <el-button v-if="row.orderStatus === 1" type="primary" icon="Van" link @click="toSendGood(row.orderId)">发货</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          class="paging"
          v-show="query.total"
          small
          layout="total, sizes, prev, pager, next, jumper" 
          :current-page="query.current" 
          :page-size="query.size"
          :total="query.total"
          @current-change="load"
          @size-change="sizeChange">
        </el-pagination>
      </el-card>
    </page-mod>

    <!-- 新增 -->
    <!-- <el-drawer 
      v-model="addShow" 
      :with-header="false" 
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true" 
      size="89.6%">
      <order-add @close="doAddClose"></order-add>
    </el-drawer> -->

    <!-- 查看详情 -->
    <el-drawer 
      v-model="infoShow" 
      :with-header="false" 
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true" 
      size="89.6%">
      <order-info :orderId="orderId" @close="doInfoClose"></order-info>
    </el-drawer>

    <!-- 发货弹窗 -->
    <el-dialog v-model="sendShow" title="订单发货" top="10vh" width="40%" center draggable>
      <el-form :model="sendGoodsForm">
        <el-form-item label="发货地址:">
          <span>{{ sendGoodsForm.address }}</span>
        </el-form-item>
        <el-form-item label="发货方式:">
          <el-radio-group v-model="sendGoodsForm.deliveryType" @change="sendGoodsForm.deliveryItemList = []">
            <el-radio label="0">无需发货</el-radio>
            <el-radio label="1">物流发货</el-radio>
            <el-radio label="2">门店配送</el-radio>
            <el-radio label="3">到店自提</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="快递单号:">
          <el-button type="primary" icon="Plus" @click="doLogisticsInfo(true)">添加快递单号</el-button>
          <el-table :data="sendGoodsForm.deliveryItemList" border>
            <el-table-column label="序号" type="index" align="center" width="60"></el-table-column>
            <el-table-column label="快递单号" prop="deliveryCode" align="center">
              <template #default="{row}">
                <el-input v-model="row.deliveryCode" placeholder="请输入快递单号" clearable></el-input>
              </template>
            </el-table-column>
            <el-table-column label="物流公司" prop="deliveryCompany" align="center">
              <template #default="{row}">
                <el-input v-model="row.deliveryCompany" placeholder="请输入物流公司" clearable></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template #default="{$index}">
                <el-button type="danger" icon="Delete" link @click="doLogisticsInfo(false, $index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="doSendGoods">发货</el-button>
        <el-button size="default" @click="sendShow = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 查看物流弹窗 -->
    <el-dialog v-model="logisticsShow" title="物流信息" top="10vh" width="50%" center draggable>
      <el-timeline>
        <el-timeline-item 
          v-for="(item, index) in logistics" 
          :key="index" 
          :timestamp="item.desc" 
          icon="Check" 
          color="#67C23A">
          {{ $date(item.time).format('YYYY-MM-DD HH:mm:ss') }}
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script setup name="orderList">
  // import orderAdd from './add.vue'
  import orderInfo from './details.vue'
  import { getOrderListPageApi, getSendGoodsAddressApi, giveOrderSendGoodsApi, getOrderLogisticsApi } from '@/api/api'
  import { reactive, toRefs, getCurrentInstance, onActivated } from 'vue'

  // 获取注册的全局实列
  const currentThis = getCurrentInstance().appContext.config.globalProperties
  const currentData = reactive({
    loading: false,
    addShow: false,
    infoShow: false,
    sendShow: false,
    logisticsShow: false,
    logistics: [],
    dates: [],
    query: {
      orderCode: '',
      orderType: '',
      orderStatus: '',
      sourceType: '',
      payType: '',
      refundStatus: '',
      startTime: '',
      endTime: '',
      current: 1,
      size: 20,
      total: 0
    },
    orderId: '',
    dataList: [],
    sendGoodsForm: {
      orderId: '',
      deliveryType: '1',
      deliveryItemList: [],
      address: ''
    }
  })
  let {loading, addShow, infoShow, sendShow, logisticsShow, logistics, dates, query, orderId, dataList, sendGoodsForm} = toRefs(currentData)

  // 查询
  function load(page) {
    currentData.loading = true
    currentData.query.current = page
    getOrderListPageApi(currentData.query).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.dataList = res.data.pages
        currentData.query.total = res.data.total
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 查看订单信息弹窗
  function toViewOrder(orderId) {
    currentData.orderId = orderId
    currentData.infoShow = true
  }

  // 查看物流信息
  function doViewLogisticsLog(deliveryCode) {
    getOrderLogisticsApi(deliveryCode).then(res => {
      if(res.code === '200') {
        currentData.logistics = res.data.data.logisticsTraceDetails
        currentData.logisticsShow = true
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 订单发货弹窗，先根据订单id查询发货地址
  function toSendGood(orderId) {
    currentData.sendGoodsForm.orderId = orderId
    getSendGoodsAddressApi(orderId).then(res => {
      if(res.code === '200') {
        currentData.sendGoodsForm.address = res.data.fullName.replace(/\//g,'') + res.data.detailAddress
        currentData.sendShow = true
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 添加快递单号
  function doLogisticsInfo(e, index) {
    if(e) {
      currentData.sendGoodsForm.deliveryItemList.push({deliveryCode: '', deliveryCompany: ''})
    } else {
      currentData.sendGoodsForm.deliveryItemList.splice(index, 1)
    }
  }
  
  // 执行发货
  function doSendGoods() {
    currentThis.$messageBox.confirm('确认发货吗？').then(() => {
      const loading = currentThis.$loading('正在处理，请耐心等待')
      giveOrderSendGoodsApi(currentData.sendGoodsForm).then(res => {
        loading.close()
        if(res.code === '200') {
          load(currentData.query.current)
          currentData.sendShow = false
          currentThis.$message.success(res.message)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 关闭新增订单弹窗
  function doAddClose(e) {
    if(e) {
      load(1)
    }
    currentData.addShow = false
  }

  // 关闭详情弹窗
  function doInfoClose() {
    load(currentData.query.current)
    currentData.infoShow = false
  }

  // 查询下单时间改变时触发
  function dateChange(e) {
    currentData.query.startTime = e ? e[0] : ''
    currentData.query.endTime = e ? e[1] : ''
  }

  function getDelivery(e) {
    let list = []
    for (const key in e) {
      list.push({name: e[key], code: key})
    }
    return list
  }

  // 重置查询
  function resetSearch() {
    currentData.query.orderCode = ''
    currentData.query.orderType = ''
    currentData.query.orderStatus = ''
    currentData.query.sourceType = ''
    currentData.query.payType = ''
    currentData.query.refundStatus = ''
    currentData.query.startTime = ''
    currentData.query.endTime = ''
    currentData.dates = []
    load(1)
  }

  function sizeChange(size) {
    currentData.query.size = size
    load(1)
  }

  onActivated(() => {
    load(currentData.query.current)
  })
</script>

<style lang="less" scoped>
.orderList{
  :deep(.el-drawer){
    .el-drawer__body{
      padding: 0 20px !important;
    }
  }
  :deep(.el-dialog){
    .el-dialog__body{
      max-height: 500px;
      overflow: hidden auto;
    }
    .el-table{
      margin-top: 10px;
    }
  }
}
</style>